package com.spring.shopping.controller;

import com.spring.shopping.entity.CartItem;
import com.spring.shopping.entity.User;
import com.spring.shopping.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> addToCart(@RequestBody Map<String, Object> requestData,
                                         HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            Integer productId = (Integer) requestData.get("productId");
            Integer quantity = (Integer) requestData.get("quantity");

            if (productId == null || quantity == null || quantity <= 0) {
                response.put("success", false);
                response.put("message", "无效的请求参数");
                return response;
            }

            cartService.addToCart(user.getId(), productId, quantity);

            int cartCount = cartService.getCartItems(user.getId()).size();

            response.put("success", true);
            response.put("message", "商品已加入购物车");
            response.put("cartCount", cartCount);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加失败: " + e.getMessage());
        }

        return response;
    }

    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateCartItem(
            @RequestParam(value = "cartId", required = true) Integer cartId,
            @RequestParam(value = "quantity", required = true) Integer quantity,
            HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            cartService.updateCartItem(cartId, quantity);

            Double totalAmount = cartService.getCartTotal(user.getId());
            int cartCount = cartService.getCartItemCount(user.getId());

            response.put("success", true);
            response.put("totalAmount", totalAmount);
            response.put("cartCount", cartCount);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败: " + e.getMessage());
        }

        return response;
    }

    @PostMapping("/remove")
    @ResponseBody
    public Map<String, Object> removeFromCart(@RequestParam("cartId") Integer cartId,
                                              HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return response;
        }

        try {
            cartService.removeFromCart(cartId);

            Double totalAmount = cartService.getCartTotal(user.getId());
            int cartCount = cartService.getCartItemCount(user.getId());

            response.put("success", true);
            response.put("totalAmount", totalAmount);
            response.put("cartCount", cartCount);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
        }

        return response;
    }

    @GetMapping("/view")
    public String viewCart(Model model, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        if (user == null) {
            return "redirect:/user/login";
        }

        List<CartItem> cartItems = cartService.getCartItems(user.getId());
        Double totalAmount = cartService.getCartTotal(user.getId());

        model.addAttribute("cartItems", cartItems);
        model.addAttribute("totalAmount", totalAmount);

        return "cart";
    }
}